package com.example.springbootparamvalidatedemo.exception;

import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author chaird
 * @create 2021-06-18 22:20
 */
@ControllerAdvice
public class AllException {
  @ExceptionHandler(value = Exception.class)
  @ResponseBody
  public String exception(Exception e) {
    return "exception处理错误！" + e.getMessage();
  }

  @ExceptionHandler(value = BindException.class)
  @ResponseBody
  public String BindException(BindException e) {
    BindingResult bindingResult = e.getBindingResult();
    String errorMesssage = "";
    for (FieldError fieldError : bindingResult.getFieldErrors()) {
      errorMesssage += fieldError.getDefaultMessage() + "!";
    }
    return "BindException处理错误！" + errorMesssage;
  }
}
